<template>
  <div class="page-refund-order-info">
    <div class="new-page-title">
      <div class="line" />
      <div class="text">
        {{ $t('order.refundProcessing') }}
      </div>
    </div>
    <div
      v-if="platInterveneSts===1 && stillAveTime"
      class="plat-intervene"
    >
      <el-icon :size="14">
        <WarningFilled />
      </el-icon>
      <span>用户申请平台介入售后，请在{{ dataForm.interventionEndTime }}前补充凭证</span>
    </div>
    <el-form
      ref="dataFormRef"
      :model="dataForm"
      label-width="auto"
      @submit.prevent
      @keyup.enter="onSubmit()"
    >
      <div class="mod-order-refundOrderInfo">
        <div class="refundId">
          <span class="title">{{ $t('order.refundId') }}:</span>
          <span class="text">{{ dataForm.refundSn }}</span>
        </div>
        <div class="content">
          <div class="order-number">
            <div class="num-cont">
              <div class="state-title">
                <div class="item">
                  <div class="title">
                    {{ $t('order.returnType') }}：
                  </div>
                  <div class="text">
                    <div v-if="dataForm.refundType === 1">
                      {{ $t("order.wholeOrderRefund") }}
                    </div>
                    <div v-if="dataForm.refundType === 2">
                      {{ $t("order.singleItemRefund") }}
                    </div>
                  </div>
                </div>
                <div class="item">
                  <div class="title">
                    {{ $t('order.returnMethod') }}：
                  </div>
                  <div class="text">
                    <div v-if="dataForm.applyType === 1">
                      {{ $t("order.onlyRefund") }}
                    </div>
                    <div v-if="dataForm.applyType === 2">
                      {{ $t("order.refundAndMoney") }}
                    </div>
                  </div>
                </div>
                <div
                  v-if="isAuth('admin:orderRefund:update') && dataForm.decisionTime && !dataForm.refundTime"
                  class="item"
                >
                  <div>{{ $t('order.wait') }}{{ dataForm.payType === 1 || dataForm.payType === 3 || dataForm.payType === 4 || dataForm.payType === 5 || dataForm.payType === 8 ? $t('order.weixin') : $t('order.alipay') }}{{ $t('order.refund') }}</div>
                </div>
              </div>
              <div class="refund-progress">
                <refund-steps :refund-detail="dataForm" />
              </div>
            </div>
          </div>
          <div class="order-state">
            <div class="state-cont">
              <div class="order-info">
                <div class="order-details refund-record-left">
                  <div class="detail-title">
                    <span class="prompt">{{ $t("order.returnDetails") }}</span>
                  </div>
                  <div class="detail-cont">
                    <div class="detail01">
                      <div class="text-width">
                        <div class="text-width-item">
                          <span class="title">{{ $t('order.number') }}：</span>
                          <span class="text">{{ dataForm.orderNumber }}</span>
                        </div>
                        <div class="text-width-item">
                          <span class="title">{{ $t('order.orderActuallyPaid') }}：</span>
                          <span class="text">{{ dataForm.orderAmount }}</span>
                        </div>
                        <div class="text-width-item">
                          <span class="title">{{ $t('order.refundAmount') }}：</span>
                          <span class="text">{{ dataForm.refundAmount + $t("admin.dollar") + "+ " + dataForm.refundScore + $t("order.integral") }}</span>
                        </div>
                        <div class="text-width-item">
                          <span class="title">{{ $t('order.applicationTime') }}：</span>
                          <span class="text">{{ dataForm.applyTime }}</span>
                        </div>
                        <div class="text-width-item">
                          <span class="title">{{ $t('order.reasonForReturn') }}：</span>
                          <span class="text">{{ dataForm.buyerReason }}</span>
                        </div>
                        <div class="text-width-item">
                          <span class="title">{{ $t('order.refundInstructions') }}：</span>
                          <span class="text">{{ dataForm.buyerDesc }}</span>
                        </div>
                        <div class="text-width-item">
                          <span class="title">{{ $t('shop.phoneNumber') }}：</span>
                          <span>{{ dataForm.buyerMobile || '-' }}</span>
                        </div>
                        <div class="text-width-item">
                          <span class="title">{{ $t('order.returnCertificate') }}：</span>
                          <div v-if="refundProofList?.length">
                            <imgGeneral :img-list="refundProofList" />
                          </div>
                          <div v-else>
                            无
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>
                </div>
                <!-- 退款记录 -->
                <div class="buyers">
                  <div class="refund-record-title detail-title">
                    <span>退款记录</span>
                    <span
                      v-if="platInterveneSts===1 && stillAveTime"
                      class="proof-btn"
                      @click="onAddProof"
                    >
                      <el-icon :size="16">
                        <Memo />
                      </el-icon>
                      <span class="txt">补充凭证</span>
                    </span>
                  </div>
                  <div class="refund-record">
                    <refundRecord :refund-detail="dataForm" />
                  </div>
                </div>
              </div>
              <div
                v-if="dataForm.applyType === 2 && dataForm.refundDelivery && (dataForm.refundDelivery.deyNu || dataForm.refundDelivery.imgs)"
                class="order-info"
              >
                <div class="order-details">
                  <div class="detail-title">
                    <span class="prompt">{{ $t("order.logisticsDetails") }}</span>
                  </div>
                  <div class="detail-cont">
                    <div class="detail01">
                      <div class="text-width">
                        <div
                          v-if="dataForm.refundDelivery && dataForm.refundDelivery.deyName"
                          class="text-width-item"
                        >
                          <span class="title">{{ $t('order.logisticsName') }}：</span>
                          <span class="text">{{ dataForm.refundDelivery.deyName }}</span>
                        </div>
                        <div
                          v-if="dataForm.refundDelivery && dataForm.refundDelivery.deyNu"
                          class="text-width-item"
                        >
                          <span class="title">{{ $t('order.trackingNumber') }}：</span>
                          <span class="text">{{ dataForm.refundDelivery.deyNu }}</span>
                        </div>
                        <div
                          v-if="dataForm.refundDelivery && dataForm.refundDelivery.senderRemarks"
                          class="text-width-item"
                        >
                          <span class="title">{{ $t('order.compradorMsg') }}：</span>
                          <span class="text">{{ dataForm.refundDelivery.senderRemarks }}</span>
                        </div>
                        <div
                          v-if="dataForm.refundDelivery && dataForm.refundDelivery.senderMobile"
                          class="text-width-item"
                        >
                          <span class="title">{{ $t('order.buyerPhone') }}：</span>
                          <span>{{ dataForm.refundDelivery.senderMobile }}</span>
                        </div>
                      </div>
                    </div>
                  </div>
                  <div class="detail-title">
                    <!-- 物流凭证 -->
                    <span>{{ $t('order.logisticsCertificate') }}</span>
                  </div>
                  <div class="buyers-info">
                    <div class="detail02">
                      <imgs-upload
                        v-model="refundDeliveryPhotos"
                        :disabled="true"
                        :modal="true"
                        :prompt="false"
                      />
                    </div>
                  </div>
                </div>
                <div class="buyers">
                  <div
                    v-if="deliveryDto"
                    class="detail-title"
                  >
                    <!-- 退款物流信息 -->
                    <span>{{ $t('order.logisticsStatus') }}：</span>
                    <span
                      v-if="deliveryDto.state === 0"
                      class="l-state"
                    >{{ $t("order.noRecord") }}</span>
                    <span
                      v-if="deliveryDto.state === 1"
                      class="l-state"
                    >{{ $t("order.collected") }}</span>
                    <span
                      v-if="deliveryDto.state === 2"
                      class="l-state"
                    >{{ $t("order.delivering") }}</span>
                    <span
                      v-if="deliveryDto.state === 3"
                      class="l-state"
                    >{{ $t("order.haveBeenReceived") }}</span>
                    <span
                      v-if="deliveryDto.state === 4"
                      class="l-state"
                    >{{ $t("order.problemPiece") }}</span>
                    <span
                      v-if="deliveryDto.state === 201"
                      class="l-state"
                    >{{ $t("order.reachTheDestinationCity") }}</span>
                  </div>
                  <div
                    v-if="deliveryDto"
                    class="logistics-box"
                  >
                    <!-- 退款时间 -->
                    <div
                      v-if="dataForm.returnMoneySts === 5 && dataForm.refundTime !== null"
                      class="item"
                    >
                      <div class="time">
                        {{ dataForm.refundTime }}
                      </div>
                      <div class="text">
                        {{ $t("refund.refundMoney") }}
                      </div>
                    </div>
                    <!-- 收货时间 -->
                    <div
                      v-if="dataForm.returnMoneySts === 5 && dataForm.receiveTime !== null"
                      class="item"
                    >
                      <div class="time">
                        {{ dataForm.receiveTime }}
                      </div>
                      <div class="text">
                        {{ $t("refund.receivedGoods") }}
                      </div>
                    </div>
                    <div
                      v-for="(trace, index) in deliveryDto.traces"
                      :key="index"
                      class="item"
                    >
                      <div class="time">
                        {{ trace.acceptTime }}
                      </div>
                      <div class="text">
                        {{ trace.acceptStation }}
                      </div>
                    </div>
                    <div
                      v-if="deliveryDto.traces &&deliveryDto.traces.length < 1"
                      class="item"
                    >
                      {{ $t("order.noLogisticsInformation") }}
                    </div>
                    <!-- 发货时间 -->
                    <div
                      v-if="dataForm.returnMoneySts >= 3 && dataForm.shipTime !== null"
                      class="item"
                    >
                      <div class="time">
                        {{ dataForm.shipTime }}
                      </div>
                      <div class="text">
                        {{ $t("refund.buyerHasShipped") }}
                      </div>
                    </div>
                    <!-- 同意退款时间 -->
                    <div
                      v-if="dataForm.returnMoneySts >= 2 && dataForm.decisionTime !== null"
                      class="item"
                    >
                      <div class="time">
                        {{ dataForm.decisionTime }}
                      </div>
                      <div class="text">
                        {{ $t("refund.merchantHasAgree") }}
                      </div>
                    </div>
                    <!-- 申请时间 -->
                    <div
                      v-if="dataForm.returnMoneySts >= 1"
                      :class="['item', dataForm.returnMoneySts >= 1?'left-line':'']"
                    >
                      <div class="time">
                        {{ dataForm.applyTime }}
                      </div>
                      <div class="text">
                        {{ $t("refund.buyerApply") }}
                      </div>
                    </div>
                  </div>
                </div>
              </div>
              <div class="item-list">
                <el-table
                  :data="prodList"
                  header-cell-class-name="table-header"
                  row-class-name="table-row"
                  :row-style="{ height:'82px'}"
                >
                  <el-table-column
                    prop=""
                    :label="$t('order.refundGoods')"
                    width="280"
                  >
                    <template #default="scope">
                      <div class="prod-info">
                        <prod-pic
                          height="60"
                          width="60"
                          :pic="scope.row.pic"
                        />
                        <div class="con">
                          <span
                            v-if="scope.row.giveawayOrderItemId"
                            class="gift-icon"
                          >{{ $t("order.giveawayPord") }}</span>
                          <span>{{ scope.row.prodName }}</span>
                          <span class="sku">{{ scope.row.skuName }}</span>
                        </div>
                      </div>
                      <!-- 赠品 -->
                      <div
                        v-if="dataForm.orderItems.length > 1"
                        class="gift-prod"
                      >
                        <div
                          v-for="(item, keys) in scope.row.giveawayList"
                          :key="keys"
                          class="item"
                        >
                          <span class="name">{{ '【' + $t("order.giveawayPord") + '】' }}{{ item.prodName }}</span>
                          <span class="num">{{ item.skuName }} ×{{ item.prodCount }}</span>
                        </div>
                      </div>
                      <!-- / 赠品 -->
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="price"
                    :label="$t('order.unitPrice')"
                  >
                    <template #default="scope">
                      <span v-if="!scope.row.giveawayOrderItemId">￥{{ price(scope.row.price) }}</span>
                      <span v-if="scope.row.giveawayOrderItemId">￥{{ getUnitPrice(scope.row.giveawayAmount,scope.row.prodCount) }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="count"
                    :label="$t('order.quantity')"
                  >
                    <template #default="scope">
                      <span>{{ scope.row.prodCount }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    prop="productTotalAmount"
                    :label="$t('order.prodTotalPrice')"
                  >
                    <template #default="scope">
                      <span v-if="dataForm.refundType === 1 && !scope.row.giveawayOrderItemId">￥{{ price(scope.row.productTotalAmount) }}</span>
                      <span v-if="dataForm.refundType === 2 && !scope.row.giveawayOrderItemId">￥{{
                        price(
                          bigProductTotalAmount(
                            scope.row.price,
                            dataForm.goodsNum
                          )
                        )
                      }}</span>
                      <span v-if="scope.row.giveawayOrderItemId">￥{{ price(scope.row.giveawayAmount) }}</span>
                    </template>
                  </el-table-column>

                  <el-table-column
                    prop="actualTotal"
                    :label="$t('order.actualAmount')"
                  >
                    <template #default="scope">
                      <span v-if="dataForm.refundType === 1 && !scope.row.giveawayOrderItemId">￥{{ price(scope.row.actualTotal) }}</span>
                      <span v-if="dataForm.refundType === 2 && !scope.row.giveawayOrderItemId">￥{{
                        price(
                          bigActualTotal(
                            scope.row.actualTotal,
                            scope.row.prodCount
                          )
                        )
                      }}</span>
                      <span v-if="scope.row.giveawayOrderItemId">-</span>
                      <el-tag
                        v-if="scope.row.shareReduce > 0 && !scope.row.giveawayOrderItemId"
                        type="danger"
                        effect="dark"
                      >
                        {{ $t("order.discount") }}
                      </el-tag>
                    </template>
                  </el-table-column>
                  <el-table-column
                    v-if="dataForm.refundType === 2"
                    prop="productTotalAmount"
                    :label="$t('order.returnAmount')"
                  >
                    <template #default="scope">
                      <span v-if="!scope.row.giveawayOrderItemId">{{
                        dataForm.refundAmount +
                          $t("admin.dollar") +
                          " + " +
                          dataForm.refundScore +
                          $t("order.integral") }}</span>
                      <span v-if="scope.row.giveawayOrderItemId">-</span>
                    </template>
                  </el-table-column>
                </el-table>
              </div>

              <div
                v-if="dataForm.returnMoneySts === 1"
                class="sellerRemark"
              >
                <div class="remark-title">
                  {{ $t("order.applyForApproval") }}：
                </div>
                <div class="remark-content">
                  <el-radio-group v-model="isAgreeRefund">
                    <el-radio :label="2">
                      {{ dataForm.applyType === 1 ? $t("order.agreeToRefundA") : $t("order.agree") }}
                    </el-radio>
                    <el-radio :label="3">
                      {{ $t("order.disagree") }}
                    </el-radio>
                  </el-radio-group>
                </div>
              </div>

              <div
                v-if="dataForm.applyType === 2 && isAgreeRefund === 2 && dataForm.returnMoneySts !== -1"
                class="sellerRemark"
              >
                <div
                  v-if="dataForm.refundDelivery"
                  class="remark-title"
                >
                  {{ $t("publics.deliveryAddr") }}：
                </div>
                <div
                  v-if="dataForm.returnMoneySts === 1"
                  class="remark-content"
                >
                  <el-select
                    v-model="dataForm.refundAddrId"
                    style="width: 350px"
                    :placeholder="$t('tip.select')"
                    @change="$forceUpdate()"
                  >
                    <el-option
                      v-for="item in addrList"
                      :key="item.refundAddrId"
                      :label="item.receiverName+'，'+item.receiverMobile+'，'+item.province + item.city + item.area + item.addr"
                      :value="item.refundAddrId"
                    />
                  </el-select>
                  <!--新建/刷新-->
                  <div
                    class="default-btn text-btn"
                    @click="refreshChange"
                  >
                    {{ $t('admin.refresh') }}
                  </div>
                  <el-divider direction="vertical" />
                  <div
                    class="default-btn text-btn"
                    @click.stop="onAddOrUpdate()"
                  >
                    {{ $t('admin.newConstruction') }}
                  </div>
                </div>
                <div
                  v-if="dataForm.refundDelivery.receiverAddr"
                  class="remark-content"
                >
                  {{ dataForm.refundDelivery.receiverName +'，'+dataForm.refundDelivery.receiverMobile+'，'+dataForm.refundDelivery.receiverAddr }}
                </div>
              </div>

              <div
                v-if="dataForm.shipTime &&!dataForm.cancelTime &&!dataForm.rejectTime"
                class="sellerRemark"
              >
                <div class="remark-title">
                  {{ $t("order.returnStatus") }}：
                </div>
                <div class="remark-content">
                  <el-radio-group
                    v-model="isReceiver"
                    :disabled="dataForm.returnMoneySts !== 3"
                  >
                    <el-radio :label="1">
                      {{ $t("order.received") }}
                    </el-radio>
                    <el-radio :label="0">
                      {{ $t("order.unreceived") }}
                    </el-radio>
                  </el-radio-group>
                </div>
              </div>

              <div
                v-if="dataForm.shipTime &&!dataForm.cancelTime &&!dataForm.rejectTime"
                class="sellerRemark"
              >
                <div class="remark-title">
                  {{ $t("order.returnRequest") }}：
                </div>
                <div class="remark-content">
                  <el-radio-group
                    v-model="isAgreeRefund"
                    :disabled="dataForm.returnMoneySts !== 3"
                  >
                    <el-radio :label="2">
                      {{ $t("order.agreeToRefundA") }}
                    </el-radio>
                    <el-radio :label="3">
                      {{ $t("order.refusalToRefund") }}
                    </el-radio>
                  </el-radio-group>
                </div>
              </div>

              <div
                v-if="isAgreeRefund === 3"
                class="sellerRemark"
              >
                <div class="input-bar denial-reason">
                  <div>
                    <div class="remark-title denial">
                      {{ $t("order.denialReason") }}：
                    </div>
                    <el-input
                      v-model="dataForm.rejectMessage"
                      type="textarea"
                      style="width: 100%;outline-style: none;"
                      :rows="6"
                      maxlength="250"
                      show-word-limit
                    />
                  </div>
                  <div class="right">
                    <div class="remark-title denial">
                      上传凭证：
                    </div>
                    <uploadProof
                      ref="uploadProofRef"
                      v-model="dataForm.voucherImgs"
                      :limit="3"
                    />
                    <span class="tips">最多上传3张</span>
                  </div>
                </div>
              </div>
              <div class="sellerRemark">
                <div
                  v-if="dataForm.returnMoneySts === 1"
                  class="input-bar"
                >
                  <div class="remark-title">
                    {{ $t('order.merchantNotes') }}：
                  </div>
                  <el-input
                    v-model="dataForm.sellerMsg"
                    type="textarea"
                    style="width: 100%;outline-style: none;"
                    maxlength="250"
                    show-word-limit
                  />
                </div>
              </div>

              <div class="btn-bar">
                <!-- 仅退款的时候进行的处理操作 -->
                <div
                  v-if="isAuth('admin:orderRefund:update') && dataForm.returnMoneySts === 1"
                  class="default-btn primary-btn"
                  @click="checkHandel()"
                >
                  {{ $t("order.confirmTreatment") }}
                </div>
                <!-- 退货退款的时候进行的处理操作 -->
                <div
                  v-if="isAuth('admin:orderRefund:update') && dataForm.returnMoneySts === 3"
                  class="default-btn primary-btn"
                  @click="returnMoneyHandle()"
                >
                  {{ $t("order.confirmTreatment") }}
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-form>
    <add-or-update
      v-if="addOrUpdateVisible"
      ref="addOrUpdateRef"
      @refresh-data-list="getRefundAddrList"
    />
    <add-proof
      v-if="addProofVisible"
      ref="addProofRef"
      :refund-detail="dataForm"
      @refresh-data="getRefundOrderInfo"
    />
  </div>
</template>

<script setup>
import { isAuth } from '@/utils'
import { ElMessage, ElMessageBox } from 'element-plus'
import AddOrUpdate from './add-or-update.vue'
import refundRecord from './components/refund-record/index.vue'
import addProof from './components/add-proof/index.vue'
import refundSteps from './components/refund-steps/index.vue'
import imgGeneral from './components/img-general/index.vue'
import Big from 'big.js'
import uploadProof from './components/upload-proof/index.vue'

const dataForm = ref({})
const uploadProofRef = ref(null) // 上传凭证组件

const { query } = useRoute()
onMounted(() => {
  dataForm.value.refundId = query.refundId || 0
  getRefundOrderInfo()
})

onBeforeUnmount(() => {
  intervenEndTimer && clearTimeout(intervenEndTimer)
})

const prodList = ref([]) // 商品列表
const isReceiver = ref(0)
const isAgreeRefund = ref(2)
const deliveryDto = ref(null)
const refundDeliveryPhotos = ref([])
// 平台介入状态 -1.没有介入 1.用户申请介入 2.平台同意介入 3.平台拒绝介入 5.平台同意退款成功 6.用户撤销
const platInterveneSts = ref(0)
const refundProofList = ref([]) // 用户申请退款凭证
const getRefundOrderInfo = () => {
  refundDeliveryPhotos.value = []
  isAgreeRefund.value = 2
  if (dataForm.value.refundId) {
    http({
      url: http.adornUrl(`/order/refund/info/${dataForm.value.refundId}`),
      method: 'get',
      params: http.adornParams()
    }).then(({ data }) => {
      dataForm.value = data
      deliveryDto.value = dataForm.value.deliveryDto
      if (dataForm.value.isReceiver) {
        isReceiver.value = 1
      } else {
        isReceiver.value = 0
      }
      if (dataForm.value.refundDelivery && dataForm.value.refundDelivery.imgs) {
        refundDeliveryPhotos.value = dataForm.value.refundDelivery.imgs
      }
      // 用户申请退款凭证
      refundProofList.value = onHandleImgs(data.photoFiles)

      // 处理商品列表
      const prods = data.orderItems
      prodList.value = prods
      if (prods && prods.length === 1 && prods[0].giveawayList && prods[0].giveawayList.length) {
        // 单个商品且有赠品时，将主商品和赠品放在同一级列表中展示
        prodList.value = [...data.orderItems, ...prods[0].giveawayList]
      }

      getRefundAddrList()
      getIsInvoiceUpload(data.orderNumber)
      platInterveneSts.value = data.platformInterventionStatus
      if (data.interventionEndTime && platInterveneSts.value === 1) {
        intervenEndTimeCountdown()
      }
    })
  }
}
// 图片处理
const onHandleImgs = (imgStr) => {
  if (imgStr) {
    return imgStr.split(',').map(url => {
      return checkFileUrl(url)
    })
  }
  return []
}

const addProofRef = ref(null)
const addProofVisible = ref(false)
const onAddProof = () => {
  addProofVisible.value = true
  nextTick(() => {
    addProofRef.value.init()
  })
}

// 平台介入时间添加凭证倒计时
let intervenEndTimer = null
const stillAveTime = ref(false)
const intervenEndTimeCountdown = () => {
  const nowTime = new Date().getTime() // 当前时间
  const endTime = new Date(dataForm.value.interventionEndTime).getTime() // 设置截止时间
  const leftTime = endTime - nowTime // 时间差

  if (leftTime >= 0) {
    stillAveTime.value = true
    // 递归每秒调用countTime方法，显示动态时间效果,
    intervenEndTimer = setTimeout(intervenEndTimeCountdown, 1000)
  } else {
    stillAveTime.value = false
    intervenEndTimer && clearTimeout(intervenEndTimer)
  }
}

const isUploadInvoice = ref(false)
const getIsInvoiceUpload = (orderNumber) => {
  http({
    url: http.adornUrl('/m/orderInvoice/is_upload'),
    method: 'get',
    params: {
      orderNumber
    }
  }).then(({ data }) => {
    isUploadInvoice.value = data
  })
}

const addOrUpdateVisible = ref(false)
const addOrUpdateRef = ref(null)
// 新增
const onAddOrUpdate = (id) => {
  addOrUpdateVisible.value = true
  nextTick(() => {
    addOrUpdateRef.value?.init(id)
  })
}

// 刷新页面
const refreshChange = () => {
  getRefundAddrList()
}

// 表单提交
const onSubmit = () => {}

const addrList = ref([])
const refundAddr = ref('')
/**
 * 加载收货地址模板
 */
const getRefundAddrList = () => {
  http({
    url: http.adornUrl('/shop/refundAddr/list'),
    method: 'get',
    params: http.adornParams()
  }).then(({ data }) => {
    addrList.value = data
    addrList.value?.forEach((item) => {
      if (item.defaultAddr) {
        dataForm.value.refundAddrId = item.refundAddrId
      }
    })
    if (dataForm.value.refundAddrId) {
      const index = addrList.value?.findIndex(item => item.refundAddrId === dataForm.value.refundAddrId)
      if (index || index === 0) {
        const refAddr = addrList.value[index]
        refundAddr.value = refAddr.province + refAddr.city + refAddr.area + refAddr.addr
      }
    }
  })
}

/**
 * 仅退款的时候，进行的退款处理操作
 * 提交处理
 */
const checkHandel = Debounce(() => {
  if (isAgreeRefund.value === 2) {
    if (isUploadInvoice.value) {
      ElMessageBox.confirm($t('order.refundTip'), $t('resource.tips'), {
        confirmButtonText: $t('resource.confirm'),
        cancelButtonText: $t('resource.cancel'),
        type: 'warning'
      }).then(() => {
        if (dataForm.value.refundType === 2 && dataForm.value.applyType === 1 && dataForm.value.status === 2) {
          checkIsLastOrderItem(handelReturnMoney)
          return
        }
        handelReturnMoney()
      }).catch(() => {
      })
      return
    } else {
      if (dataForm.value.refundType === 2 && dataForm.value.applyType === 1 && dataForm.value.status === 2) {
        checkIsLastOrderItem(handelReturnMoney)
        return
      }
      handelReturnMoney()
    }
    return
  }
  handelReturnMoney()
})

const isProcessing = ref(false) // 是否正在处理订单
const handelReturnMoney = async () => {
  const tempRefundAddrId = isAgreeRefund.value === 2 ? dataForm.value.refundAddrId : undefined
  if (isProcessing.value) {
    return
  }
  if (isAgreeRefund.value === 3) {
    if (!dataForm.value.rejectMessage?.trim()) {
      ElMessage({
        message: $t('order.denialReason') + $t('publics.noNull'),
        type: 'error',
        duration: 1500
      })
      return
    }
    if (!dataForm.value.voucherImgs) {
      ElMessage({
        message: '请上传凭证',
        type: 'error',
        duration: 1500
      })
      return
    }
  }
  isProcessing.value = true
  isAgreeRefund.value !== 3 && (dataForm.value.voucherImgs = '')
  if (isAgreeRefund.value === 3) {
    const saveFileRes = await uploadProofRef.value.saveAttachFileToPlat()
    if (!saveFileRes) {
      // eslint-disable-next-line require-atomic-updates
      isProcessing.value = false
      return
    }
  }
  http({
    url: http.adornUrl('/order/refund/process'),
    method: 'put',
    data: http.adornData({
      refundId: dataForm.value.refundId,
      refundSts: isAgreeRefund.value,
      refundSn: dataForm.value.refundSn,
      rejectMessage: dataForm.value.rejectMessage,
      sellerMsg: dataForm.value.sellerMsg,
      refundAddrId: tempRefundAddrId,
      shopImgUrls: dataForm.value.voucherImgs // 凭证
    })
  }).then(() => {
    getRefundOrderInfo()
    isProcessing.value = false
    ElMessage({
      message: $t('publics.operation'),
      type: 'success',
      duration: 1500,
      onClose: () => {
      }
    })
  }).catch(() => {
    isProcessing.value = false
  })
}

/**
 * 是否为最后一个退款项
 */
const checkIsLastOrderItem = (fn) => {
  http({
    url: http.adornUrl('/order/refund/isLastRefund'),
    method: 'get',
    params: http.adornParams({
      refundSn: dataForm.value.refundSn
    })
  }).then(({ data }) => {
    if (data) {
      if (dataForm.value.freightAmount.toFixed(2) + '' != '0.00') {
        ElMessageBox.confirm($t('order.lastProdRefundTip').replace('[d]', dataForm.value.freightAmount.toFixed(2) + ' '), $t('resource.tips'), {
          confirmButtonText: $t('resource.confirm'),
          cancelButtonText: $t('resource.cancel'),
          type: 'warning'
        }).then(() => {
          fn()
        })
      } else {
        fn()
      }
    } else {
      fn()
    }
  })
}

/**
 * 确定退款
 */
const returnMoneyHandle = async () => {
  if (isProcessing.value) {
    return
  }
  if (isAgreeRefund.value === 3) {
    if (!dataForm.value.rejectMessage?.trim()) {
      ElMessage({
        message: $t('order.denialReason') + $t('publics.noNull'),
        type: 'error',
        duration: 1500
      })
      return
    }
    if (!dataForm.value.voucherImgs) {
      ElMessage({
        message: '请上传凭证',
        type: 'error',
        duration: 1500
      })
      return
    }
  }
  isProcessing.value = true
  isAgreeRefund.value !== 3 && (dataForm.value.voucherImgs = '')
  if (isAgreeRefund.value === 3) {
    const saveFileRes = await uploadProofRef.value.saveAttachFileToPlat()
    if (!saveFileRes) {
      // eslint-disable-next-line require-atomic-updates
      isProcessing.value = false
      return
    }
  }
  http({
    url: http.adornUrl('/order/refund/returnMoney'),
    method: 'put',
    data: http.adornData({
      refundId: dataForm.value.refundId,
      refundSts: isAgreeRefund.value,
      refundSn: dataForm.value.refundSn,
      rejectMessage: dataForm.value.rejectMessage,
      sellerMsg: dataForm.value.sellerMsg,
      isReceiver: isReceiver.value,
      shopImgUrls: dataForm.value.voucherImgs // 凭证
    })
  }).then(() => {
    isProcessing.value = false
    getRefundOrderInfo()
    ElMessage({
      message: $t('publics.operation'),
      type: 'success',
      duration: 1500,
      onClose: () => {
      }
    })
  }).catch(() => {
    isProcessing.value = false
  })
}

// 精度运算-乘法
const bigProductTotalAmount = (a, b) => {
  return new Big(a).times(b)
}

// 精度运算-除法
const bigActualTotal = (a, b) => {
  if (a == null) {
    return ''
  }
  return new Big(a).div(b).times(dataForm.value.goodsNum).toFixed(2)
}

const price = (value) => {
  if (!value) {
    return 0.00
  }
  return Number(value).toFixed(2)
}
const getUnitPrice = (value, count) => {
  if (!value) {
    return 0.00
  }
  return new Big(value).div(count).toFixed(2)
}
</script>

<style lang="scss" scoped>
  @use './index.scss';
</style>
